<script lang="ts" setup name="FMyVideo">
// FMyVideo 组件用于直播视频播放，使用TCPlayer实现
import { ref, onMounted, onUnmounted, nextTick, computed, watch, unref } from 'vue'

// 导入TCPlayer库（假设已在项目中引入）
// @ts-ignore
import TCPlayer from 'tcplayer.js'
import 'tcplayer.js/dist/tcplayer.min.css'

const props = defineProps({
    detail: {
        type: Object,
        default: () => {}
    }
})

const sources = computed(() => {
    if (!props.detail.live_url) return []
    const isM3u8 = props.detail.live_url.includes('m3u8')
    return [
        {
            src: props.detail.live_url, // 播放地址
            type: !isM3u8 ? 'video/mp4' : 'application/x-mpegURL' // 视频格式
        }
    ]
})

let player: any = null
const playerRef = ref<HTMLElement>()

watch(() => props.detail, (value) => {
    if (!value) return
    console.log(1111)

    initPlayer()
}, { immediate: true })

onMounted(async () => {
})

onUnmounted(() => {
    destroyPlayer()
})

function initPlayer () {
    if (!playerRef.value) return
    // 销毁已存在的播放器
    destroyPlayer()
    console.log(unref(sources))

    // 初始化TCPlayer
    player = TCPlayer(playerRef.value, {
        sources: unref(sources),
        autoplay: true,
        width: '100%',
        height: '100%',
        controlBarPosition: 'bottom',
        controlBarShowTime: 5000,
        fitVideoSize: 'auto',
        live: false,
        volume: 0.5
    })
    // 监听播放器事件
    player.on('play', () => {
        console.log('视频开始播放')
    })
    player.on('error', (e: any) => {
        console.error('播放器错误:', e)
    })
}

function destroyPlayer () {
    if (player) {
        player.destroy()
        player = null
    }
}
</script>

<template>
  <div class="video">
    <!-- TCPlayer播放器容器 -->
    <video ref="playerRef" class="tcplayer-container"></video>
  </div>
</template>

<style scoped lang="scss">
.video {
  width: 100%;
  height: 40vh;
  background-color: #000;
  position: relative;
  .tcplayer-container {
    width: 100%;
    height: 100%;
    background-color: #000;
    position: relative;
    z-index: 1;
  }
}
</style>
